package com.liang.gulimall.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.liang.common.utils.HttpUtils;
import com.liang.gulimall.member.entity.MemberLevelEntity;
import com.liang.gulimall.member.exception.PhoneExistException;
import com.liang.gulimall.member.exception.UsernameExistException;
import com.liang.gulimall.member.vo.SocialUser;
import com.liang.gulimall.member.vo.UserLoginVo;
import com.liang.gulimall.member.vo.UserRegisterVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.common.utils.PageUtils;
import com.liang.common.utils.Query;

import com.liang.gulimall.member.dao.MemberDao;
import com.liang.gulimall.member.entity.MemberEntity;
import com.liang.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(UserRegisterVo vo) {
        //检查手机号用户名是否唯一
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUsername());

        MemberEntity memberEntity = new MemberEntity();
        //获取默认等级
        MemberLevelEntity memberLevelEntity= baseMapper.getDefauleLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUsername());
        memberEntity.setNickname(vo.getUsername());//昵称默认
        //密码需要加密
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        memberEntity.setCreateTime(new Date());
        //保存其他默认信息

        baseMapper.insert(memberEntity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile>0){
            throw new PhoneExistException();
        }

    }

    @Override
    public void checkUsernameUnique(String username) throws  UsernameExistException{
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count>0){
            throw  new UsernameExistException();
        }

    }

    @Override
    public MemberEntity login(UserLoginVo vo) {
        String loginAccount = vo.getLoginAccount();
        String password = vo.getPassword();
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAccount).or().eq("mobile", loginAccount));
        if (memberEntity==null){
            return null;
        }
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(password, memberEntity.getPassword());
        if (matches){
            //登录OK，密码匹配
            return memberEntity;
        }
        return null;
    }

    /**
     * 社交登录注册合并逻辑
     * @param socialUser
     * @return
     */
    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        String uid = socialUser.getUid();
        //判断用户是否登录过系统
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity!=null){
            //已经登陆过,更新
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpireIn(socialUser.getExpires_in());
            baseMapper.updateById(memberEntity);
            return memberEntity;
        }else {
            //没有登陆过进行注册
            MemberEntity register = new MemberEntity();
            register.setExpireIn(socialUser.getExpires_in());
            register.setAccessToken(socialUser.getAccess_token());
            register.setSocialUid(socialUser.getUid());
            register.setCreateTime(new Date());

            //查询其他信息（昵称等）
            Map<String,String> map=new HashMap<>();
            map.put("access_token",socialUser.getAccess_token());
            map.put("uid",socialUser.getUid());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get",
                    new HashMap<>(), map);
            if (response.getStatusLine().getStatusCode()==200){
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSONObject.parseObject(json);
                String nikName = jsonObject.getString("name");//昵称
                String city = jsonObject.getString("location");
                String description = jsonObject.getString("description");
                String profile_image_url = jsonObject.getString("profile_image_url");
                String gender = jsonObject.getString("gender");//性别，m：男、f：女
                register.setNickname(nikName);
                register.setCity(city);
                register.setGender("m".equals(gender)?1:0);
                register.setSign(description);
                register.setHeader(profile_image_url);
            }
            baseMapper.insert(register);
            return register;
        }
    }

}